/*
 * Copyright 2011-2012 Redia A/S
 * 
 * This file is part of Redias Library App for Android.
 *
 *  Redia Library App for Android is free software: you can redistribute it and/or modify
 *  it under the terms of the GNU General Public License as published by
 *  the Free Software Foundation, either version 3 of the License, or
 *  (at your option) any later version.
 *
 *  Redia Library App for Android is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *  GNU General Public License for more details.
 *  
 *  You should have received a copy of the GNU General Public License
 *  along with Redia Library App for Android.  If not, see <http://www.gnu.org/licenses/>.
 */

package dk.redia.libraryapp;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import dk.redia.lib.log.Log;
import android.view.View;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.ProgressBar;
import android.widget.Toast;
import dk.redia.lib.utils.AppApplication;
import dk.redia.libraryapp.authentication.Authentication;
import dk.redia.libraryapp.authentication.AuthenticationListener;

public class AuthenticateActivity extends Activity {

	public static final String EXTRAS_KEY_CALLBACK_CLASS = "callbackClass";

	private static final String logTag = "AuthenticateActivity";
	
    private Class<?> callBackClass;
	
	/** Called when the activity is first created. */
	@Override
	public void onCreate(Bundle savedInstanceState) {
	    super.onCreate(savedInstanceState);
	    Bundle extras = getIntent().getExtras();
	    if (extras==null) {
	    	throw new RuntimeException("No extras included when creating AuthenticateActivity");
	    }
	    Object callBackClassObj = extras.get(AuthenticateActivity.EXTRAS_KEY_CALLBACK_CLASS);
	    if (callBackClassObj==null) {
	    	throw new RuntimeException("No callback class specified when creating an AuthenticationActivity");
	    }
	    callBackClass = (Class<?>)callBackClassObj;
	    if (Authentication.getInstance().isAuthenticated()) {
	    	Log.w(AuthenticateActivity.logTag, "Already authenticated when creating AuthenticationActivity. Doing immediate callback.");
	    	callback();
	    } else {
	    	// Only show stuff if user isn't currently authenticated
		    setContentView(R.layout.authenticate);
		    getBorrowerCardIdEditText().setText(Authentication.getInstance().getBorrowerCardId());
		    getBorrowerPasswordEditText().setText(Authentication.getInstance().getBorrowerPassword());
		    getSavingCredentialsCheckBox().setChecked(Authentication.getInstance().savingCredentials());
	    }
	}
	
	private void callback() {
		if (callBackClass!=null) {
			Intent intent = new Intent(this, callBackClass);
			if (getIntent().getExtras()!=null) {
				intent.putExtras(getIntent().getExtras());
			}
			startActivity(intent);
			finish();
		} else {
			Log.w(AuthenticateActivity.logTag, "Unable to do callback. No callback class specified.");
		}
	}
	
	private CheckBox getSavingCredentialsCheckBox() {
		return (CheckBox)findViewById(R.id.authenticateRememberCredentialsCheckBox);
	}

	private EditText getBorrowerCardIdEditText() {
		return (EditText)findViewById(R.id.authenticateBorrowerCardIdEditText);
	}
	
	private EditText getBorrowerPasswordEditText() {
		return (EditText)findViewById(R.id.authenticateBorrowerPasswordEditText);
	}
	
//	private void setMessage(String message) {
//		((TextView)findViewById(R.id.authenticateMessageTextView)).setText(message);
//	}

	private void setAuthenticating(boolean authenticating) {
		ProgressBar throbber = (ProgressBar)findViewById(R.id.authenticateProgressBar);
		EditText userNameEditText = (EditText)findViewById(R.id.authenticateBorrowerCardIdEditText);
		EditText passwordEditText = (EditText)findViewById(R.id.authenticateBorrowerPasswordEditText);
		userNameEditText.setEnabled(!authenticating);
		passwordEditText.setEnabled(!authenticating);
		throbber.setVisibility(authenticating ? View.VISIBLE : View.INVISIBLE);
				
	}
	
	public void onLoginButtonClick(View button) {
		setAuthenticating(true);
		String borrowerCardId = getBorrowerCardIdEditText().getText().toString();
		String borrowerPassword = getBorrowerPasswordEditText().getText().toString();
		Authentication.getInstance().setBorrowerCardId(borrowerCardId);
		Authentication.getInstance().setBorrowerPassword(borrowerPassword);
		Authentication.getInstance().authenticate(new AuthenticationListener() {
			
			public void succeeded() {
				callback();
				
				if (!Authentication.getInstance().savingCredentials()) {
					unsetStoredCredentials();
				}
				
			}
			
			public void failed(String message) {
				setAuthenticating(false);
				AppApplication.toast("Login fejlede: " + message, Toast.LENGTH_LONG);
//				setMessage("Login fejlede: " + message);
				
				if (!Authentication.getInstance().savingCredentials()) {
					unsetStoredCredentials();
				}
			}
		});
	}
	
	private void unsetStoredCredentials() {
		Authentication.getInstance().setBorrowerCardId("");
		Authentication.getInstance().setBorrowerPassword("");
	}
	
	public void onCancelButtonClick(View button) {
		finish();
	}
	
	public void onRememberCredentialsCheckBoxClicked(View v) {
		Log.d(logTag, "Toggling 'save credentials'");
		Authentication.getInstance().setSaveCredentials(((CheckBox)v).isChecked());		
	}
	
}
